package com.intmall.flink.operator;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class TransformFlatMapTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> stream = env.fromElements(
                new Event("Mary", "./home", 1000L),
                new Event("Bob", "./cart", 2000L)
        );

        stream.flatMap(new MyFlatMap()).print();

        // Lambda表达式，需要设置返回值
        stream.flatMap((Event value, Collector<String> out) -> {
            out.collect(value.getUser());
            out.collect(value.getUrl());
        }).returns(Types.STRING)
                .print("flatMap");

        env.execute();
    }

    public static class MyFlatMap implements FlatMapFunction<Event, String> {
        @Override
        public void flatMap(Event value, Collector<String> out) throws Exception {
            if (value.getUser().equals("Mary")) {
                out.collect(value.getUser());
            } else if (value.getUser().equals("Bob")) {
                out.collect(value.getUser());
                out.collect(value.getUser());
            }
        }
    }
}
